package com.magold.skill;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.magold.logic.LogicComponentFinder;
import com.magold.physics.MagoldPhysicsConnector;
import com.magold.skill.BaseSkill.SkillListener;

public class SuppressSkill extends BaseSkill implements SkillListener {
	private Body[] mAllSuppressingBodies;
	private Vector2[] mLinearVelocityBuffer;
	private float[] mAngularVelocityBuffer;
	private boolean mSavedBuffer;
	
	public SuppressSkill(Body[] pAllSuppressingBodies) {
		mAllSuppressingBodies = pAllSuppressingBodies;
		
		mLinearVelocityBuffer = new Vector2[mAllSuppressingBodies.length];
		for (int i = 0; i < mLinearVelocityBuffer.length; i++) {
			mLinearVelocityBuffer[i] = new Vector2();
		}
		
		mAngularVelocityBuffer = new float[mAllSuppressingBodies.length];
		
		addSkillListener(this);
	}
	
	@Override
	protected void onSkillLaunching(float pSecondsElapsed) {
		if (!mSavedBuffer) {
			saveVelocityData();
		}
		
		for (Body b : mAllSuppressingBodies) {
			b.setLinearVelocity(0, 0);
			b.setAngularVelocity(0);
		}
	}
	
	private void saveVelocityData() {
		int i = 0;
		for (Body b : mAllSuppressingBodies) {
			Vector2 buf = b.getLinearVelocity();
			mLinearVelocityBuffer[i].set(buf);
			mAngularVelocityBuffer[i] = b.getAngularVelocity();
			i++;
		}
		
		mSavedBuffer = true;
	}

	@Override
	public void onStop(BaseSkill pSkill) {
		if (pSkill != this) return;
		
		assert mSavedBuffer;
		
		int i = 0;
		for (Body b : mAllSuppressingBodies) {
			b.setLinearVelocity(mLinearVelocityBuffer[i]);
			b.setAngularVelocity(mAngularVelocityBuffer[i]);
			i++;
			
			MagoldPhysicsConnector connector = LogicComponentFinder.findConnector(b);
			connector.setGravityScale(1);
		}
		
		// set flag to dirty.
		mSavedBuffer = false;
	}
	
	@Override
	public void onLaunch(BaseSkill pSkill) {
		if (pSkill != this) return;
		
		for (Body b : mAllSuppressingBodies) {
			MagoldPhysicsConnector connector = LogicComponentFinder.findConnector(b);
			connector.setGravityScale(0);
		}
		mSavedBuffer = false;
	}

}
